import 'package:coin_genarate/coin_generate.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:lifecycle_monitor/lifecycle_monitor.dart';
import 'package:oktoast/oktoast.dart';
import 'package:route_manager/wx_navigator.dart';
import 'package:wallet_authentication/PIN/models/wallet_info_model.dart';
import 'package:wallet_authentication/module_config.dart';
import 'package:wallet_authentication/utils/aes_util.dart';

class RecoverMnemonicPage extends StatefulWidget {
  const RecoverMnemonicPage({Key key}) : super(key: key);

  @override
  _RecoverMnemonicPageState createState() => _RecoverMnemonicPageState();
}

class _RecoverMnemonicPageState extends State<RecoverMnemonicPage> {
  List<TextEditingController> controllerList = [];
  List<String> hintMnemonicWordNumber = [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "10",
    "11",
    "12"
  ];
  bool isButtonEnable = false;

  @override
  void initState() {
    super.initState();

    for (int i = 0; i < 12; i++) {
      controllerList.add(TextEditingController());
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          elevation: 0,
          title: Text("${WXLang.$t("authentication_recover_wallet", package: ModuleConfig.moduleName)}"),
        ),
        body: Container(
          padding: EdgeInsets.all(10),
          child: Column(
            children: <Widget>[
              Container(
                margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Text("${WXLang.$t("authentication_input_mnemonic_words", package: ModuleConfig.moduleName)}"),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(10, 8, 10, 0),
                child: Text(
                  "${WXLang.$t("authentication_recover_wallet_info", package: ModuleConfig.moduleName)}",
                  style: TextStyle(fontSize: 13, color: Colors.red),
                ),
              ),
              Container(
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0x13000000), width: 1.0),
                    borderRadius: BorderRadius.circular(8)),
                margin: EdgeInsets.symmetric(
                  vertical: 15,
                ),
                padding: EdgeInsets.fromLTRB(10, 13, 10, 20),
                child: _buildGrid(),
              ),
              Container(
                child: MaterialButton(
                  color: Colors.blue,
                  disabledColor: Color(0xFFD6D6D6),
                  padding: EdgeInsets.symmetric(horizontal: 65, vertical: 13),
                  child: Text(
                    "${WXLang.$t("authentication_confirm", package: ModuleConfig.moduleName)}",
                    // style: Theme.of(context).textTheme.headline4,
                    style: TextStyle(
                        color: Color(0xDDFFFFFF),
                        fontWeight: FontWeight.w800,
                        letterSpacing: 1,
                        fontSize: 14),
                  ),
                  onPressed: isButtonEnable ? () {
                    StringBuffer stringBuffer = StringBuffer();
                    for (int i = 0; i < controllerList.length; i++) {
                      stringBuffer.write(controllerList[i].text);
                      if (i != controllerList.length - 1) {
                        stringBuffer.write(" ");
                      }
                    }

                    print('stringBuffer---' + stringBuffer.toString());

                    if (CoinGenerateManager().validateMnemonic(stringBuffer.toString())) {
                      // PinCode保存操作 | 保存钱包名称
                      WalletInfo.savePinCodeName();
                      WalletInfo.saveWalletName();

                      //跳转前先保存bool变量和助记词
                      SpUtil.putBool("verified_mnemonic", true);
                      SpUtil.putString("mnemonic_list", AESUtil.encryptString(stringBuffer.toString()));
                      /// 注册息屏逻辑
                      StateObserver().registerObserver();

                      //跳主页
                      WXNavigator.pushNamedAndRemoveUntil("/wallet_home", (route) => false,
                          context: context, moduleName: "wallet_home");
                    } else {
                      showToast("${WXLang.$t("authentication_illegal_mnemonic", package: ModuleConfig.moduleName)}");
                    }
                  } : null,
                ),
              ),
            ],
          ),
        ));
  }

  Widget _buildGrid() {
    return GridView.count(
        physics: NeverScrollableScrollPhysics(),
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        shrinkWrap: true,
        childAspectRatio: 1.9,
        crossAxisCount: 4,
        children: List.generate(12, (i) {
          return Container(
              padding: EdgeInsets.all(1),
              child: TextField(
                onChanged: (String value){
                  for(int j=0; j<controllerList.length ; j++){
                    if(controllerList[j].text.trim().isEmpty) {
                      setState(() {
                        isButtonEnable = false;
                      });
                      return;
                    }
                  }

                  setState(() {
                    isButtonEnable = true;
                  });
                },
                controller: controllerList[i],
                decoration: InputDecoration(
                  hintText: hintMnemonicWordNumber[i],
                ),
              ));
        }));
  }
}
